using NodeCanvas.Variables;
using UnityEngine;

namespace NodeCanvas.BehaviourTrees
{
	[AddComponentMenu("")]
	[Name("Iterate")]
	[Category("Decorators")]
	[Description("Iterate a game object list and execute the child node for each object in the list. Keeps iterating until the Termination Condition is met or the whole list is iterated and return the child node status")]
	[Icon("List")]
	public class BTIterator : BTDecorator
	{
		public enum TerminationConditions
		{
			FirstSuccess = 0,
			FirstFailure = 1,
			None = 2
		}

		[BlackboardOnly]
		public BBGameObjectList list;

		[BlackboardOnly]
		public BBGameObject current;

		public BBInt maxIteration;

		public TerminationConditions terminationCondition = TerminationConditions.None;

		public bool resetIndex = true;

		private int currentIndex;

		protected override Status OnExecute(Component agent, Blackboard blackboard)
		{
			if (!base.decoratedConnection)
			{
				return Status.Resting;
			}
			if (list.value == null || list.value.Count == 0)
			{
				return Status.Failure;
			}
			current.value = list.value[currentIndex];
			base.status = base.decoratedConnection.Execute(agent, blackboard);
			if (base.status == Status.Success && terminationCondition == TerminationConditions.FirstSuccess)
			{
				return Status.Success;
			}
			if (base.status == Status.Failure && terminationCondition == TerminationConditions.FirstFailure)
			{
				return Status.Failure;
			}
			if (base.status != Status.Running)
			{
				if (currentIndex == list.value.Count - 1 || currentIndex == maxIteration.value - 1)
				{
					return base.status;
				}
				base.decoratedConnection.ResetConnection();
				currentIndex++;
				return Status.Running;
			}
			return base.status;
		}

		protected override void OnReset()
		{
			if (resetIndex || currentIndex == list.value.Count - 1 || currentIndex == maxIteration.value - 1)
			{
				currentIndex = 0;
			}
		}
	}
}
